package com.alks.function.service.impl.stockdept.pcfactorystockquery;

import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.entity.data.entity.BaseModel;
import com.alks.entity.data.entity.HgMtl;
import com.alks.entity.data.entity.HgMtlRelation;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.vo.controller.stockdept.HgMtlRelationVo;
import com.alks.function.mapper.stockdept.pcfactorystockquery.HgMtlMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.HgMtlRelationMapper;
import com.alks.function.service.stockdept.pcfactorystockquery.IHgMtlService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author MS
 * @since 2025/6/414:44
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class HgMtlServiceImpl implements IHgMtlService {
    private final HgMtlMapper hgMtlMapper;
    private final HgMtlRelationMapper hgMtlRelationMapper;

    @Override
    public List<HgMtl> list(String search) {
        // 获取数据
        LambdaQueryWrapper<HgMtl> queryWrapper = new LambdaQueryWrapper<HgMtl>()
                .and(StringUtils.isNotEmpty(search),w->w
                .like(HgMtl::getMtlNoHg, search).or()
                .like(HgMtl::getMtlNameEng, search))
                .eq(BaseModel::getDelFlag,0);
        return hgMtlMapper.selectList(queryWrapper);

    }

    @Override
    public void detailAdd(HgMtlRelation relation) {
        // 检验是否有重复物料
        LambdaQueryWrapper<HgMtlRelation> queryWrapper = new LambdaQueryWrapper<HgMtlRelation>()
                .eq(HgMtlRelation::getMtlNo, relation.getMtlNo())
                .eq(HgMtlRelation::getMtlName, relation.getMtlName())
                .eq(StringUtils.isNotBlank(relation.getMtlColor()),HgMtlRelation::getMtlColor, relation.getMtlColor())
                .isNull(StringUtils.isBlank(relation.getMtlColor()),HgMtlRelation::getMtlColor)
                .eq(StringUtils.isNotBlank(relation.getMtlSpec()),HgMtlRelation::getMtlSpec, relation.getMtlSpec())
                .isNull(StringUtils.isBlank(relation.getMtlSpec()),HgMtlRelation::getMtlSpec)
                .eq(StringUtils.isNotBlank(relation.getMtlUnit()),HgMtlRelation::getMtlUnit, relation.getMtlUnit())
                .isNull(StringUtils.isBlank(relation.getMtlUnit()),HgMtlRelation::getMtlUnit)
                .eq(HgMtlRelation::getDelFlag, 0);
        HgMtlRelation queryRelation = hgMtlRelationMapper.selectOne(queryWrapper);
        if (queryRelation!=null) {
            if (queryRelation.getHgId().equals(relation.getHgId())){
                return;
            }
            throw new ServiceErrorException("物料已关联海关编码");
        }
        // 如果关联数据与当前数据相同，则不进行操作
        //写入关联数据
        relation.setSysUser(UserIdThread.get().getUserName());
        relation.setSysDate(LocalDateTime.now());
        hgMtlRelationMapper.insert(relation);
    }

    @Override
    public void detailUpdate(HgMtlRelation relation) {
        hgMtlRelationMapper.updateById(relation);
    }

    @Override
    public HgMtlRelationVo detailQueryByMtl(HgMtlRelation relation) {
        return hgMtlRelationMapper.hgDetailQueryByMtl(relation);
    }

    @Override
    public List<HgMtlRelationVo> detailQueryByMtlList(List<HgMtlRelation> relationList) {
        if (ArrayUtils.isEmpyt(relationList)){
            return null;
        }
        return hgMtlRelationMapper.hgDetailQueryBatchByMtl(relationList);
    }

    @Override
    public Map<String, HgMtlRelationVo> detailMapQueryByMtlList(List<HgMtlRelation> relationList) {
        // 去重
        relationList = relationList.stream()
                .map(dto -> new HgMtlRelation()
                        .setMtlNo(dto.getMtlNo())
                        .setMtlName(dto.getMtlName())
                        .setMtlSpec(dto.getMtlSpec())
                        .setMtlColor(dto.getMtlColor())
                        .setMtlUnit(dto.getMtlUnit()))
                .distinct()
                .collect(Collectors.toList());
        // 获取数据
        List<HgMtlRelationVo> hgMtlRelations = this.detailQueryByMtlList(relationList);
        if (ArrayUtils.isNotEmpty(hgMtlRelations)) {
            Map<String, HgMtlRelationVo> hgMap = hgMtlRelations.stream()
                    .collect(Collectors.toMap(
                            vo -> Arrays.asList(
                                    Optional.ofNullable(vo.getMtlNo()).orElse(""),
                                    Optional.ofNullable(vo.getMtlName()).orElse(""),
                                    Optional.ofNullable(vo.getMtlColor()).orElse(""),
                                    Optional.ofNullable(vo.getMtlSpec()).orElse(""),
                                    Optional.ofNullable(vo.getMtlUnit()).orElse("")
                            ).toString(),
                            Function.identity()
                    ));
            return hgMap;
        }
        return null;
    }

    @Override
    public void detailUpByMtl(HgMtlRelation relation) {
        // 根据物料信息更新海关编码
        LambdaUpdateWrapper<HgMtlRelation> updateWrapper = new LambdaUpdateWrapper<HgMtlRelation>()
                .eq(HgMtlRelation::getMtlNo, relation.getMtlNo())
                .eq(HgMtlRelation::getMtlName, relation.getMtlName())
                .eq(StringUtils.isNotBlank(relation.getMtlColor()),HgMtlRelation::getMtlColor, relation.getMtlColor())
                .isNull(StringUtils.isBlank(relation.getMtlColor()),HgMtlRelation::getMtlColor)
                .eq(StringUtils.isNotBlank(relation.getMtlSpec()),HgMtlRelation::getMtlSpec, relation.getMtlSpec())
                .isNull(StringUtils.isBlank(relation.getMtlSpec()),HgMtlRelation::getMtlSpec)
                .eq(StringUtils.isNotBlank(relation.getMtlUnit()),HgMtlRelation::getMtlUnit, relation.getMtlUnit())
                .isNull(StringUtils.isBlank(relation.getMtlUnit()),HgMtlRelation::getMtlUnit)
                .eq(HgMtlRelation::getDelFlag, 0);
        List<HgMtlRelation> relationList = hgMtlRelationMapper.selectList(updateWrapper);
        if (ArrayUtils.isNotEmpty(relationList)){
            //确认数据存在则修改
            updateWrapper.set(HgMtlRelation::getHgId, relation.getHgId());
            hgMtlRelationMapper.update(null, updateWrapper);
        }else{
            //不存在则写入
            relation.setHgRelId(null);
            hgMtlRelationMapper.insert(relation);
        }

    }

    public void add(HgMtl hgMtl) {
        // 校验是否重复
        LambdaQueryWrapper<HgMtl> queryWrapper = new LambdaQueryWrapper<HgMtl>()
                .eq(HgMtl::getMtlNoHg, hgMtl.getMtlNoHg())
                .eq(HgMtl::getDelFlag, 0);
        hgMtlMapper.selectCount(queryWrapper);
        if (hgMtlMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("编码已存在");
        }
        // 补充基础数据
        hgMtl.setSysUser(UserIdThread.get().getUserName());
        hgMtl.setSysDate(LocalDateTime.now());
        hgMtlMapper.insert(hgMtl);
    }

    public void update(HgMtl hgMtl) {        // 补充基础数据
        hgMtl.setUpdateUser(UserIdThread.get().getUserName());
        hgMtl.setUpdateDate(LocalDateTime.now());
        hgMtlMapper.updateById(hgMtl);
    }

    public void delete(Long id) {
        // 删除主表
        hgMtlMapper.logicDelete(id);

        // 连携删除关联表
        hgMtlRelationMapper.logicDeleteByHgId(id);
    }

    public List<HgMtlRelation> detailList(Long id) {
        LambdaQueryWrapper<HgMtlRelation> queryWrapper = new LambdaQueryWrapper<HgMtlRelation>()
                .eq(HgMtlRelation::getHgId, id)
                .eq(BaseModel::getDelFlag, 0);
        return hgMtlRelationMapper.selectList(queryWrapper);
    }
}
